package Tetris;

import javax.swing.*;
import javax.swing.KeyStroke;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;


public class Tetris {
    /*
    数据的声明,这些变量均是用于游戏面板
     */
    final static int ROWS = 20;
    final static int COLS = 12;
    int row;
    int col;
    JLabel scoreLabel;
    int[][] currentBlock;
    static int[][] data;
    JTextArea[][] text;
    int[][] nextBlock;
    static int[][] nextData;
    JTextArea[][] nextText;
    JPanel nextBlockPanel;
    Score score;
    JFrame frame;

    private volatile boolean isPaused = false; // 暂停标志位（volatile确保可见性）
    private final Object pauseLock = new Object(); // 线程锁

    // 初始化数据
    public Tetris() {
        data = new int[ROWS][COLS];
        text = new JTextArea[ROWS][COLS];
        score = new Score();
        nextData = new int[4][4];
        nextText = new JTextArea[4][4];
        frame = initFrame();
        initMenu();
        initDraw();
    }

    private void initMenu(){
        JMenuBar menuBar = new JMenuBar();

        JMenu Menu = new JMenu("菜单");
        // 创建一个菜单项
        JMenuItem pauseItem = new JMenuItem("暂停游戏");
        pauseItem.setAccelerator(KeyStroke.getKeyStroke("P"));
        // 为菜单项绑定点击事件

        pauseItem.addActionListener(e -> {
            isPaused = !isPaused;
        });

        JMenuItem history = new JMenuItem("历史记录");
        history.setAccelerator(KeyStroke.getKeyStroke("H"));
        history.addActionListener(e -> {
           //在终端输出历史记录
            System.out.println("成绩如下：");
            for(Integer i : score.list){
                System.out.println(i);
            }
        });

        Menu.add(pauseItem);
        Menu.add(history);
        menuBar.add(Menu);
        frame.setJMenuBar(menuBar);
    }

    /**
     * 做一个单独的界面（呈现得分数据）
     */

    private void menu_score(){

    }



    private void initDraw(){
        JPanel leftPanel = initBlack(ROWS,COLS,data,text);
        frame.add(leftPanel, BorderLayout.CENTER);
        JPanel rightPanel = initRightFrame(frame);

        JPanel space = new JPanel();
        space.setBackground(Color.WHITE);
        space.setPreferredSize(new Dimension(120, 80));
        rightPanel.add(space);



        JPanel makePersonPanel = new JPanel();
        makePersonPanel.setBackground(Color.WHITE);
        makePersonPanel.setPreferredSize(new Dimension(120, 40));
        JLabel makePersonLabel = new JLabel(" 制作者：QiuShui");
        makePersonPanel.add(makePersonLabel);
        rightPanel.add(makePersonPanel);


        JPanel scorePanel = new JPanel();
        scorePanel.setPreferredSize(new Dimension(120, 80));
        scorePanel.setBackground(Color.WHITE);
        scoreLabel = new JLabel(" 得分：" + score.getScore());
        scoreLabel.setText(" 得分：" + score.getScore());
        scoreLabel.setFont(new Font("宋体", Font.BOLD, 20));
        scorePanel.add(scoreLabel);
        rightPanel.add(scorePanel);

        nextBlockPanel = initBlack(4,4,nextData,nextText);
        nextBlockPanel.setPreferredSize(new Dimension(120, 120));
        rightPanel.add(nextBlockPanel, BorderLayout.CENTER);
    }

    private JFrame initFrame(){
        JFrame frame = new JFrame("俄罗斯方块");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 800);
        frame.setVisible(true);
        frame.setLayout(new BorderLayout());  //这里调整frame的布局方式
        frame.addKeyListener(new KeyListener() {
            @Override
            public void keyTyped(KeyEvent e) {
            }

            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_A) {
                    col = Tool.moveLeft(data, text, currentBlock, row, col);
                }
                else if (e.getKeyCode() == KeyEvent.VK_D) {
                    col = Tool.moveRight(data, text, currentBlock, row, col);
                }
                else if (e.getKeyCode() == KeyEvent.VK_S) {
                    row = Tool.moveDown(data, text, currentBlock, row, col);
                }
                else if (e.getKeyCode() == KeyEvent.VK_W) {
                    Tool.clear(data, text, currentBlock, row, col);

                    int[][] temBlock = Tool.rotate(currentBlock,row,col,data);
                    if(temBlock !=null){
                        currentBlock = temBlock;
                    }
                    Tool.draw(data, text, currentBlock, row, col);
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {

            }
        });
        return frame;
    }

    /**
     * 初始化左侧面板
     * @param row 行数
     * @param col 列数
     * @param data 保存该格子的数据
     * @param text 显示数据
     * @return 生成一个面板返回
     */
    private JPanel initBlack(int row, int col, int[][]data, JTextArea[][] text){
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBackground(Color.LIGHT_GRAY);
        JPanel gridPanel = new JPanel(new GridLayout(row, col, 1, 1)); // 格子间距设为1px
        gridPanel.setBackground(Color.BLACK); // 网格背景设为黑色，用于显示边界


        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                data[i][j] = 0;
                text[i][j] = new JTextArea(1,1);
                panel.add(text[i][j], BorderLayout.CENTER);
                text[i][j].setBackground(Color.WHITE);
                text[i][j].setEditable(false);
                gridPanel.add(text[i][j]);
            }
        }
        panel.add(gridPanel, BorderLayout.CENTER);
        return panel;
    }

    private JPanel initRightFrame(JFrame frame){
        // 右侧面板（EAST区域）
        JPanel rightPanel = new JPanel();
        rightPanel.setBackground(Color.WHITE);
        rightPanel.setPreferredSize(new Dimension(210, 800));  //设置右侧面板的宽度
        frame.add(rightPanel, BorderLayout.EAST);
        return rightPanel;
    }

    public void game() throws InterruptedException {
        nextBlock = Tool.getData();
        while (true) {
            row = 0;
            col = COLS/2;
            currentBlock = nextBlock;
            nextBlock = Tool.getData();
            if(Tool.gameOver(currentBlock, data, col)) break;
            if(nextBlock[0].length == 4){
                Tool.draw(nextData, nextText, nextBlock, 1, 0);
            }else{
                Tool.draw(nextData, nextText, nextBlock, 1, 1);
            }

            for (int i = 0; i <= ROWS; i++) {
                while (isPaused) { // 循环检查，避免虚假唤醒

                }
                if(Tool.fall(data , currentBlock, row, col)){
                    Tool.clear(data, text, currentBlock, row, col);
                    row++;
                    Tool.draw(data, text, currentBlock, row, col);
                }else{
                    score.getScore(row, col, currentBlock, data, text);
                    scoreLabel.setText(" 得分：" + score.getScore());
                    //System.out.println("得分：" + score.getScore());
                    break;
                }
                Thread.sleep(1000);
            }
            if(nextBlock[0].length == 4){
                Tool.clear(nextData, nextText, nextBlock, 1, 0);
            }else{
                Tool.clear(nextData, nextText, nextBlock, 1, 1);
            }
        }
        System.out.println("游戏结束");
        System.out.println(score.getScore());

        frame.dispose();
    }

}